package Demo01;

public class Main {
}

class Solution {
    public static void main(String[] args) {
        char[][] arr = {
                {'A','B','C','E'},
                {'S','F','C','S'},
                {'A','D','E','E'}
        };
        System.out.println(exist(arr, "ABCCED"));
    }
    public static boolean exist(char[][] board, String word) {

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if(existPart(board, i, j, word, 0)) {
                    return true;
                }
            }
        }
        return existPart(board, 0, 0, word, 0);
    }

    private static boolean existPart(char[][] arr, int n, int m, String word, int sign) {
        if (sign == word.length()) {
            return true;
        }
        if (n < 0 || m < 0 || n == arr.length || m == arr[0].length||arr[n][m]!=word.charAt(sign)) {
            return false;
        }
        char tmp = arr[n][m];
        arr[n][m] = '0';
        boolean res = existPart(arr, n - 1, m, word, sign + 1)
                ||
                existPart(arr, n + 1, m, word, sign + 1)
                ||
                existPart(arr, n, m - 1, word, sign + 1)
                ||
                existPart(arr, n, m + 1, word, sign + 1);
        arr[n][m] = tmp;
        return res;
    }

}